package com.lsabcd.dubbo.test;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

public class Window {
    // ms
    private int interval;
    private List<WindowItem> list;
    private WindowItem head;

    private Long startTime = null;


    private ReentrantLock lock = new ReentrantLock();


    public Window(int interval,Long startTime){
        this.interval = interval;
        this.startTime = startTime;
        list = new LinkedList<>();
    }

    public void addItem(WindowItem item){
        list.add(item);
    }


    public void addItemV1(WindowItem item) {
        lock.lock();
        if (head == null) {
            list = new LinkedList<WindowItem>();
            head = item;
            list.add(item);
        } else {
            if (item.getTime().getTime() - head.getTime().getTime() > interval) {
                cleanV1();
                list = new LinkedList<WindowItem>();
                head = item;
                list.add(item);
            } else {
                list.add(item);
            }
        }
        lock.unlock();
    }

    public void cleanV1(){

        list = new LinkedList<WindowItem>();
    }


    public int getInterval() {
        return interval;
    }

    public void setInterval(int interval) {
        this.interval = interval;
    }

    public List<WindowItem> getList() {
        return list;
    }

    public void setList(List<WindowItem> list) {
        this.list = list;
    }

    public WindowItem getHead() {
        return head;
    }

    public void setHead(WindowItem head) {
        this.head = head;
    }

    public Long getStartTime() {
        return startTime;
    }

    public void setStartTime(Long startTime) {
        this.startTime = startTime;
    }


    @Override
    public String toString() {
        return "Window{" +
                "list=" + list +
                '}';
    }
}
